<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/10/9
 * Time: 11:25
 */
namespace App\Service\Api;

use App\Http\Model\MongoDB\DistributionConfig;
use App\Http\Model\Mysql\BrandModel;
use App\Http\Model\Mysql\CouponConnectionModel;
use App\Http\Model\Mysql\CouponModel;
use App\Http\Model\Mysql\ProductCatModel;
use App\Http\Model\Mysql\ProductIntegralModel;
use App\Http\Model\Mysql\ProductModel;
use App\Http\Model\Mysql\ProductObjectModel;
use App\Http\Model\Mysql\AttributeValueModel;
use App\Http\Model\Mysql\CategoryModel;
use App\Http\Model\Mysql\OrderCommentModel;
use App\Http\Model\Mysql\UserModel;
use App\Http\Model\Mysql\ProductCommissionModel;
use App\Http\Model\Mysql\ProductMaterialModel;
use App\Utils\WechatUtil;
use Carbon\Carbon;

class GoodsService extends BaseService
{
    /**
     * 获取商品列表页
     * @param array $query  搜索条件
     * @param int $page     当前页数
     * @param string $name  排序名称
     * @param string $sort  排序方式
     * @return array
     */
    public function goodsList(array $query, int $page = 1, string $name = 'sorting', string $sort = 'desc')
    {
        $user_info   =  auth('api')->user();
        $user_id     =  $user_info->uid ?? NULL;
        /**
         * 搜索条件
         */
        $model  =   ProductModel::query()->sell();

        if (isset($query['cat_id']) && $query['cat_id'] != NULL) {
            $query['cat_id']    =   CategoryModel::where(['unique_id' => $query['cat_id']])->value('id') ?? 0;
            $all_cat    =   CategoryModel::getSubCat($query['cat_id']);
            //连接子查询
            /*$model->whereHas('category', function ($query) use($all_cat) {
                $query->whereIn('cat_id', $all_cat);
            });*/
            $model->Join('mini_product_cat', function ($join) {
                $join->on('mini_product.id', '=', 'mini_product_cat.product_id');
            })->whereIn('mini_product_cat.cat_id', $all_cat);
        }

        if (isset($query['keyword']) && !empty($query['keyword'])) {
            $where[]    =   ['mini_product.name', 'like', '%' . trim($query['keyword']) . '%'];
            $model->where($where);
        }

        if (isset($query['brand_id']) && $query['brand_id'] != NULL) {
            if (is_string($query['brand_id'])) {
                $query['brand_id']    =   BrandModel::where(['unique_id' => $query['brand_id']])->value('id') ?? 0;
            }
            $brand_id   =   $query['brand_id'];
            $model->where('brand_id', '=', $brand_id);
        }

//        dd($model->toSql());
        $count  =   $model->count();
        $list   =   $model->limit(self::PAGE_LIMIT)->offset(($page - 1) * self::PAGE_LIMIT)
                    ->select(['mini_product.id', 'unique_id', 'name', 'brand_id', 'sell_price', 'original_price', 'stock', 'cover_pic', 'virtual_sales', 'sku_code', 'real_sales', 'sorting'])
                    ->orderBy($name, $sort)->get()->each(function (&$item) {
                    });

        if ($list->isEmpty()) {
            return [true, []];
        } else {
            /**
             * 查看商品的优惠券
             */
            $total_good =   [];
            $list_good  =   $list->toArray();
            foreach ($list_good as $item) {
                $total_good[]   =   $item['id'];
            }

            [$flag, $coupon_list]    =   (new CouponService())->couponSpecific($total_good, $user_id);

            foreach ($list_good as &$item) {
                $item['coupon_list']   =   [];
                if($flag && !empty($coupon_list['good_coupon']) && isset($coupon_list['good_coupon'][$item['id']])) {
                    $item['coupon_list']    =   array_merge($item['coupon_list'], $coupon_list['good_coupon'][$item['id']]);
                }
                /**
                 * 判断是否有满减或折扣
                 */
                $item['sub_coupon'] =   $item['discount_coupon']    =   false;
                foreach ($item['coupon_list'] as $item_coupon) {
                    if ($item_coupon['connect_type'] == CouponConnectionModel::GOOD_CONNECT) {
                        if ($item_coupon['coupon']['type'] == CouponModel::DECREASE_TYPE) {
                            $item['sub_coupon']     =   true;
                        }

                        if ($item_coupon['coupon']['type'] == CouponModel::DISCOUNT_TYPE) {
                            $item['discount_coupon']    =   true;
                        }
                    }
                }
            }

            return [true, [
                'count' =>  $count,
                'current'=> $page,
                'pages' =>  ceil($count / self::PAGE_LIMIT),
                'list'  =>  $list_good
            ]];
        }
    }

    /**
     * 获取商品详情信息
     * @param string $good_id 商品唯一标识符
     * @return array
     */
    public function goodsDetail(string $good_id)
    {
        //查看商品详情
        $detail =   ProductModel::with([
                        'objectUrl' => function ($query) {
                            $query->where(['is_delete' => ProductObjectModel::NOT_DELETE])->select(['id', 'product_id', 'object_type', 'object_url']);
                        },
                        'specs' =>  function ($query) {
                            $query->select(['id', 'product_id', 'attr_list', 'sell_price', 'spec_pic', 'sku_code', 'stock']);
                        },
                    ])->where(['unique_id' => $good_id])->sell()->select(['id', 'unique_id', 'name', 'sku_code', 'sell_price', 'original_price', 'cost_price', 'cover_pic', 'cover_video', 'virtual_sales', 'sorting', 'stock', 'unit', 'weight', 'limit_number', 'desc', 'spec_remark', 'detail', 'shop_id'])->first();
        if (empty($detail)) {
            return [false, '商品不存在'];
        } else {
            $spec_desc  =   [];
            /**
             * 商品规格数据的处理
             */
            if (!empty($detail->specs)) {
                foreach ($detail->specs as &$item) {
                    $attr_list   =   json_decode($item->attr_list, true);
                    $single_desc =   $single_value  =   [];
                    foreach ($attr_list as $key => $value) {
//                        $spec_desc[$key][]  =   $value;         //array_unique(array_merge($value, $spec_desc[$key] ?? []));
                        $single['name'] =   $key;
                        $single['value']=   $value;
                        $single_desc[]  =   $single;
                        if (isset($spec_desc[$key])) {
                            $spec_value =   array_merge(is_array($spec_desc[$key]['value']) ? $spec_desc[$key]['value'] : [$spec_desc[$key]['value']], [$single['value']]);
                            $spec_desc[$key]['value']   =   $spec_value;
                        } else {
                            $spec_desc[$key]=   $single;
                        }
                        $single_value[] =   $value;
                    }
                    $item->attr_list    =   $single_desc;
                    $item->attr_value   =   $single_value;

                    /**
                     * 判断积分
                     */
                    $integral_info  =   ProductIntegralModel::where(['good_id' => $detail->id, 'spec_id' => $item->id, 'is_shelf' => 1])->select(['id', 'good_id', 'spec_id', 'integral', 'is_vip'])->first();
                    if (empty($integral_info)) {
                        $item->allow_integral   =   0;
                        $item->integral =   0;
                        $item->is_vip   =   0;
                    } else {
                        $item->allow_integral   =   1;
                        $item->integral =   $integral_info->integral;
                        $item->is_vip   =   $integral_info->is_vip;
                    }
                }
            }

            $detail->spec_desc  =   array_values(array_map(function (&$item) {
                $item['value']  =   is_array($item['value']) ? array_unique($item['value']) : [$item['value']];
                return $item;
//                return is_array($item) ? array_values(array_unique($item)) : $item;
            }, $spec_desc));
            $user_info   =  auth('api')->user();
            $user_id     =  $user_info->uid ?? NULL;
            [$flag, $coupon_list]   =   (new CouponService())->couponSpecific([$detail->id], $user_id, $detail->shop_id);
            $total_coupon   =   [];
            if ($flag) {
                if(!empty($coupon_list['good_coupon']) && isset($coupon_list['good_coupon'][$detail->id])) {
                    $total_coupon   =   array_merge($total_coupon, $coupon_list['good_coupon'][$detail->id]);
                }

                if (!empty($coupon_list['shop_coupon']) && isset($coupon_list['shop_coupon'][$detail->shop_id])) {
                    $total_coupon   =   array_merge($total_coupon, $coupon_list['shop_coupon'][$detail->shop_id]);
                }

                $detail->coupon_list=  $total_coupon;
            }

            $detail->detail         =   empty($detail->detail) ? [] : json_decode($detail->detail, true);
            //计算商品可以返佣价格
            /**
             * 查看店铺佣金配置
             */
            $detail->allow_share    =   false;
            $shop_config    =   DistributionConfig::where(['companyId' => '621b9cc5-11b3-4d0e-ad82-981351e25336'])->select(['distriSwitch', 'distriRate', 'liveBoxDistriLevel', 'commissionCalculate', 'commissionShowType'])->first();
            if (empty($shop_config) || !$shop_config['distriSwitch']) {
                $detail->share_price    =   0.00;
            } else {
                $commission_config  =   ProductCommissionModel::where(['product_id' => $detail->id])->select(['commission_price', 'commission_rate', 'is_commission'])->first();
                if (!empty($commission_config) && $commission_config->is_commission == 1) {
                    $detail->allow_share    =   true;
                }
                if ($shop_config['commissionShowType'] == 1) {
                    $detail->share_price    =   empty($commission_config) ? 0.00 : round($commission_config->commission_rate * $detail->sell_price / 100, 2);
                } else {
                    $detail->share_price    =   empty($commission_config) ? 0.00 : $commission_config->commission_price;
                }
            }
            return [true, $detail];
        }
    }

    /**
     * 获取商品评价
     * @param int $good_id
     * @param array $query
     * @param int $page
     * @return array
     */
    public function goodsComment(int $good_id, array $query = [], int $page = 1)
    {
        $where['good_id']   =   $good_id;
        $where['is_delete'] =   OrderCommentModel::NOT_DELETE;
        if (!empty($query['good_level'])) {
            switch ($query['good_level']) {
                case 1:
                    $where[]    =   ['good_star', '>=', '1'];
                    $where[]    =   ['good_star', '<=', '2'];
                    break;

                case 2:
                    $where['good_star'] =   3;
                    break;

                case 3:
                    $where[]    =   ['good_star', '>=', '4'];
                    $where[]    =   ['good_star', '<=', '5'];
                    break;
            }
        }

        if (!empty($query['has_pic'])) {
            $where['has_pic']   =   $query['has_pic'];
        }

        $count  =   OrderCommentModel::where($where)->count();
        $list   =   OrderCommentModel::where($where)->orderBy('created_at', 'desc')->select(['id', 'order_id', 'good_id', 'user_id', 'seller_star', 'good_star', 'logistic_star', 'comment', 'comment_pic', 'created_at'])
                    ->get()->each(function (&$item) {
                        $item->user_info    =   UserModel::where(['uid' => $item->user_id])->select(['uid', 'nickname', 'relname', 'headimg'])->first();
                        $item->comment_time =   $item->created_at->toDateTimeString();
                        $item->comment_pic  =   json_decode($item->comment_pic, true);
                        unset($item->created_at);
                    });
        if ($list->isEmpty()) {
            return [true, []];
        } else {
            return [true, [
                'count' =>  $count,
                'current'=> $page,
                'pages' =>  ceil($count / self::PAGE_LIMIT),
                'list'  =>  $list->toArray()
            ]];
        }
    }

    /**
     * 热门商品推荐
     * @param int $good_id
     * @param int $page
     * @return array
     */
    public function goodsHot(int $good_id, int $page = 1)
    {
        $model  =   ProductModel::query()->where(['is_hot' => 1])->where('id', '!=', $good_id)->sell();
        $count  =   $model->count();
        $list   =   $model->limit(self::PAGE_LIMIT)->offset(($page - 1) * self::PAGE_LIMIT)->select(['id', 'unique_id', 'name', 'brand_id', 'sell_price', 'original_price', 'stock', 'cover_pic', 'virtual_sales', 'sku_code', 'real_sales', 'sorting'])
                    ->orderBy('sorting', 'desc')->get()->each(function (&$item) {
                    });

        if ($list->isEmpty()) {
            return [true, []];
        } else {
            $list_good  =   $list->toArray();

            return [true, [
                'count' =>  $count,
                'current'=> $page,
                'pages' =>  ceil($count / self::PAGE_LIMIT),
                'list'  =>  $list_good
            ]];
        }
    }

    /**
     * 商品发圈素材
     * @param int $good_id
     * @param int $page
     * @return array
     */
    public function goodsMaterial(int $good_id, int $page = 1)
    {
        $list   =   ProductMaterialModel::with([
                        'user'  =>  function ($query) {
                            $query->select(['uid', 'nickname', 'headimg', 'phone']);
                        }
                    ])->where(['product_id' => $good_id, 'is_delete' => ProductCommissionModel::NOT_DELETE])->offset(($page - 1) * self::PAGE_LIMIT)->limit(self::PAGE_LIMIT)->select(['id', 'uid', 'product_id', 'material_title', 'material_video', 'material_images', 'material_counter'])->get()->each(function (&$item) {
                        $item->material_images  =   empty($item->material_images) ? [] : json_decode($item->material_images, true);
                    });

        return [true, $list->isEmpty() ? [] : $list->toArray()];
    }

    /**
     * 商品详情海报
     * @param int $good_id
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function goodsPoster(int $good_id)
    {
        $user_info  =   request()->post('api_user');
        $good_info  =   ProductModel::where(['id' => $good_id])->select(['id', 'unique_id', 'name'])->first();
        if (empty($good_info)) {
            return [false, '商品不存在'];
        }

        [$flag, $result]    =   WechatUtil::getUnlimitedCode(['scene' => 'detail'], $user_info['user_id'] ?? 0);    //, 'page' => '/pages/goods/detail?good_id=' . $good_info->unique_id
        if ($flag && isset($result['img_path'])) {
            return [true, [
                'user_info' =>  $user_info,
                'code_img'  =>  $result['img_path'],
            ]];
        } else {
            return [false, '二维码生成失败'];
        }
    }

}
